package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.AdminRoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminRole;
import com.xxxx.server.service.IAdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-08-17
 */
@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements IAdminRoleService {

    @Resource
    private AdminRoleMapper adminRoleMapper;

    /**
     * 查询所有admin
     *
     * @return
     */
    @Override
    public List<Admin> initAllRoles(String name) {

        return adminRoleMapper.initAllRoles(name);
    }

    /**
     * 逻辑删除admin
     *
     * @param id
     * @return
     */
    @Override
    public Integer updateAdmin(Integer id) {

        return adminRoleMapper.updateAdmin(id);
    }

    /**
     * 更新用户角色
     *
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    public void updateAdminRole(Integer adminId, String rids) {

        // 判断用户是否有用户管理角色
        Integer count = adminRoleMapper.countAdminRoleByAdminId(adminId);

        // 如果存在用户角色记录，则先删除
        if (count > 0) {
            adminRoleMapper.deleteAdminRoleByAdminId(adminId);
        }

        // 判断角色id是否为空
        if (rids != null) {
            // 用户角色集合
            List<AdminRole> adminRoles = new ArrayList<>();

            // 将字符串转化为数组
            String[] roleIdArray = rids.split(",");

            // 遍历角色id，封装用户角色对象
            for (String roleId : roleIdArray) {
                AdminRole adminRole = new AdminRole();

                adminRole.setRid(Integer.parseInt(roleId));

                adminRole.setAdminId(adminId);

                adminRoles.add(adminRole);
            }

            AdminRoleServiceImpl adminRoleService = new AdminRoleServiceImpl();

            adminRoleService.saveBatch(adminRoles);
        }
    }
}
